﻿using BZ.Logger;
using BZVision;
using NDK.Module.BLL;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Module.StationLogic;
using NDK.Motion.BLL;
using NDK.Motion.Frm;
using NDK.Motion.MachineManager;
using NDK.Motion.Sys;
using NDK.Utils;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using VisionPlatform;

namespace NDK.Frm
{
    public partial class Frm_Main : Form
    {
        #region 解决闪烁问题
        /// <summary>
        /// 解决闪烁问题
        /// </summary>
        //protected override CreateParams CreateParams
        //{
        //    get
        //    {
        //        CreateParams cp = base.CreateParams;
        //        cp.ExStyle |= 0x02000000;
        //        return cp;
        //    }
        //}
        #endregion

        #region 窗体对象实例，单例模式,保证整个工程只有一个实例
        private static Frm_Main _instance;
        private static readonly object singletonLock = new object();
        public static Frm_Main Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new Frm_Main();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion

        #region 线程定义
        public Thread thread_TriColorLamp = null; //三色灯线程
        public Thread thread_AxisStatus = null; //监控轴报警线程
        public Thread Thread_Home = null; //机台初始化线程
        public Thread Thread_ScanButton = null;////扫描机台按钮、光幕线程

        public Thread Thread_MonitorEMGSignal = null;//监控急停信号
        public Thread Thread_MonitorDoorGSignal = null;//监控急停信号

        public Thread Thread_UserOptionCheckBFMessage = null;//监控系统是否闲置
        #endregion

        private void ProTypeListItemsInit()
        {
            tscb_ProTypeList.Items.Clear();
            foreach (var item in Common.ProductTypeMeasureItemEnableList)
            {
                tscb_ProTypeList.Items.Add(item.ProductType);
            }
            tscb_ProTypeList.SelectedItem = Common.CurProType;

            Common.CurProTypeMeasureItems = Common.ProductTypeMeasureItemEnableList.Find(x => x.ProductType.Equals(Common.CurProType));
            if (Common.CurProTypeMeasureItems == null)
            {
                Common.AppendUiLog.Log($"选择当前产品类型异常", LogType.Error);
            }
        }

        private Frm_Main()
        {
            InitializeComponent();
            Common.AppendUiLog = GlobleLoggerConfiguration.Config();

            Common.AppendCtLog00 = Station00CtLogger.Config();
            Common.AppendCtLog01 = Station01CtLogger.Config();
            Common.AppendCtLog02 = Station02CtLogger.Config();
            Common.AppendCtLog03 = Station03CtLogger.Config();
            Common.AppendCtLog04 = Station04CtLogger.Config();
            Common.AppendCtLog05 = Station05CtLogger.Config();
            Common.AppendCtLog06 = Station06CtLogger.Config();
            Common.AppendCtLog07 = Station07CtLogger.Config();
            Common.AppendCtLog08 = Station08CtLogger.Config();
            Common.AppendCtLog09 = Station09CtLogger.Config();
            Common.AppendCtLog10 = Station10CtLogger.Config();
            Common.AppendCtLog11 = Station11CtLogger.Config();
            Common.AppendCtLog12 = Station12CtLogger.Config();
            Common.AppendCtLog13 = Station13CtLogger.Config();
            Common.AppendCtLog14 = Station14CtLogger.Config();
            Common.AppendCtLog15 = Station15CtLogger.Config();
            // machine = MachineFactory.Instance.CreateMachine();
            //AppDomain.CurrentDomain.SetData("machine", machine);
            ProTypeListItemsInit();
            #region 五分钟没有鼠标键盘响应就上锁(指纹锁权限要用的)
            Common.msg = new UserOptionCheckBFMessage();
            Application.AddMessageFilter(Common.msg);
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
            #endregion

            Common.CheckTimeRefreshAction += Common_CheckTimeRefreshAction;
            PublicMethod.SafeDoorWorkAction += PublicMethod_SafeDoorWorkAction;
        }

        DateTime CurCheckTime;
        System.Windows.Forms.Timer CheckTimeTimer;
        

        private void Common_CheckTimeRefreshAction(string obj)
        {
            CurCheckTime = DateTime.Parse(obj);
            Lab_CurCheckTime.Text = $"上次点检时间:{obj}";
            if (CheckTimeTimer == null)
            {
                CheckTimeTimer = new System.Windows.Forms.Timer()
                {
                    Interval = 500,
                };
                CheckTimeTimer.Tick += CheckTimeTimer_Tick;
            }
        }

        void CheckTimeTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                var time = (CurCheckTime.AddHours(12) - DateTime.Now).TotalHours;
                if (time < 0)
                {
                    Common.IsCheckOK = false;
                    panel1.BackColor = Color.Red;
                    lab_NextCheckTime.Text = "请立即点检";
                }
                else
                {
                    Common.IsCheckOK = true;
                    panel1.BackColor = Color.Green;
                    lab_NextCheckTime.Text = $"剩余: {time:f2} H";
                }
            }
            catch (Exception EX)
            {

            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            #region UI
            //修改主窗体的样式
            StyleUtils.MainFormStyle(this);
            //修改子窗体的样式
            StyleUtils.SetMdiStyle(this, Frm_Home.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Setting.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Login.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Statistics.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Alarm2.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_YieldStatistics.Instance, 0, tlp_Menu.Height);

            tlp_FrmContainer.Controls.Add(Frm_Home.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Setting.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Login.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Statistics.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Alarm2.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_YieldStatistics.Instance, 0, 2);

            Frm_Home.Instance.Dock = DockStyle.Fill;
            Frm_Setting.Instance.Dock = DockStyle.Fill;
            Frm_Login.Instance.Dock = DockStyle.Fill;
            Frm_Statistics.Instance.Dock = DockStyle.Fill;
            Frm_Alarm2.Instance.Dock = DockStyle.Fill;
            Frm_YieldStatistics.Instance.Dock = DockStyle.Fill;
            Frm_Home.Instance.Show();
            #endregion

            ucBtnExt_MachineInfo.BtnText = Common.ProjectName;
            this.WindowState = FormWindowState.Maximized;


            if (!Common.IsOfflineMode)
            {
                //三色灯线程开启
                Instance.thread_TriColorLamp = new Thread(PublicMethod.ThreadMethod_TriColorLamp);
                Instance.thread_TriColorLamp.IsBackground = true;
                Instance.thread_TriColorLamp.Start();

                //监控轴报警
                Instance.thread_AxisStatus = new Thread(PublicMethod.ThreadMethod_AxisStatus);
                Instance.thread_AxisStatus.IsBackground = true;
                Instance.thread_AxisStatus.Start();

                //监控EMG急停信号
                Instance.Thread_MonitorEMGSignal = new Thread(PublicMethod.ThreadMethod_EMGStatus);
                Instance.Thread_MonitorEMGSignal.IsBackground = true;
                Instance.Thread_MonitorEMGSignal.Start();

                //监控门信号
                Instance.Thread_MonitorDoorGSignal = new Thread(PublicMethod.ThreadMethod_DoorStatus);
                Instance.Thread_MonitorDoorGSignal.IsBackground = true;
                Instance.Thread_MonitorDoorGSignal.Start();

                //复位线程开启
                Instance.Thread_Home = new Thread(PublicMethod.ThreadMethod_Home);
                Instance.Thread_Home.IsBackground = true;
                Instance.Thread_Home.Start();


                //按钮、光幕
                Instance.Thread_ScanButton = new Thread(PublicMethod.ThreadMethod_ScanButton);
                Instance.Thread_ScanButton.IsBackground = true;
                Instance.Thread_ScanButton.Start();

                //5分钟系统闲置加更改登录状态
                Instance.Thread_UserOptionCheckBFMessage = new Thread(background_DoWork);
                Instance.Thread_UserOptionCheckBFMessage.IsBackground = true;
                Instance.Thread_UserOptionCheckBFMessage.Start();


                Thread thread1 = new Thread(PublicMethod.ThreadMethod_PLCHeart);
                thread1.IsBackground = true;
                thread1.Start();

                Thread thread2 = new Thread(PublicMethod.ThreadMethod_ScanOmronPLC);
                thread2.IsBackground = true;
                thread2.Start();

                Thread thread3 = new Thread(PublicMethod.ThreadMethod_Alarm);
                thread3.IsBackground = true;
                thread3.Start();

                if (Common.IsIniSucess == true)//Common.isFingerPrintInitialed
                {
                    Thread.Sleep(2000);
                    Common.AppendUiLog.Log("设备初始化成功，请复位", LogType.Info);
                    MachineStatusManager.CurrentMachineStatus = MachineStatus.Initialized;
                }
                else
                {
                    Thread.Sleep(2000);
                    Common.AppendUiLog.Log("设备初始化失败，请检查", LogType.Error);
                    MachineStatusManager.CurrentMachineStatus = MachineStatus.Unknown;
                }
                //CheckTimeTimer.Start();
            }
        }



        #region 快捷键
        /// <summary>
        /// 按ESC退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_ESCKeyPress(object sender, KeyEventArgs e)
        {
            if (e.Shift && e.Control && e.KeyCode == Keys.B)//调用Block点检
            {
                if (Common.PointCheck_Block)
                {
                    Common.PointCheck_Block = false;
                    Common.AppendUiLog.Log("气缸信号RunB00000");
                }
                else
                {
                    Common.PointCheck_Block = true;
                    Common.AppendUiLog.Log("气缸信号RunB11111");
                }
            }
            if (e.Shift && e.Control && e.KeyCode == Keys.G)//调用GRR点检
            {
                if (Common.PointCheck_ProductGRR)
                {
                    Common.PointCheck_ProductGRR = false;
                    Common.AppendUiLog.Log("气缸信号RunR00000");
                }
                else
                {
                    Common.PointCheck_ProductGRR = true;
                    Common.AppendUiLog.Log("气缸信号RunR11111");
                }
            }
        }
        #endregion 按ESC键，退出程序

        #region 主界面按钮点击事件
        private void ucBtnImg_Home_BtnClick(object sender, EventArgs e)
        {
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Home.Instance.Show();
            Frm_Statistics.Instance.Hide();
            Frm_Alarm2.Instance.Hide();
            Frm_YieldStatistics.Instance.Hide();
        }

        private void ucBtnImg_Setting_BtnClick(object sender, EventArgs e)
        {
            if (Common.username == "Apple" || Common.username == "superadmin" || Common.username == "EN" || Common.username == "Battery QM")
            {
                Frm_Home.Instance.Hide();
                Frm_Login.Instance.Hide();
                Frm_Setting.Instance.Show();
                Frm_Statistics.Instance.Hide();
                Frm_Alarm2.Instance.Hide();
                Frm_YieldStatistics.Instance.Hide();
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (Common.username == "Battery QM")
            {
                //Frm_Setting.Instance.sti_TrackSetting.Visible = true;
                //Frm_Setting.Instance.superTabItem2.Visible = true;
                //Frm_Setting.Instance.superTabItem4.Visible = true;
                //Frm_Setting.Instance.superTabItem1.Visible = true;
                //Frm_Setting.Instance.tab_SizeConfig.Visible = true;
                //Frm_Setting.Instance.superTabItem8.Visible = true;
                //Frm_Setting.Instance.dgv_Home.Enabled = false;
                //Frm_Setting.Instance.dgv_SizeConfig.Enabled = false;
            }
            else if (Common.username == "EN" || Common.username == "Apple" || Common.username == "superadmin")
            {
                //Frm_Setting.Instance.sti_TrackSetting.Visible = true;
                //Frm_Setting.Instance.superTabItem2.Visible = true;
                //Frm_Setting.Instance.superTabItem4.Visible = true;
                //Frm_Setting.Instance.superTabItem1.Visible = true;
                //Frm_Setting.Instance.tab_SizeConfig.Visible = true;
                //Frm_Setting.Instance.superTabItem8.Visible = true;
                //Frm_Setting.Instance.dgv_Home.Enabled = true;
                //Frm_Setting.Instance.dgv_SizeConfig.Enabled = true;
            }
        }

        private void ucBtnImg_Vision_BtnClick(object sender, EventArgs e)
        {
            if (Common.username == "EN" || Common.username == "Apple" || Common.username == "superadmin")
            {
                if (!Frm_VisionDebug.Instance.Visible)
                {
                    Frm_VisionDebug.Instance.Show(this);
                }
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void ucBtnImg_Statistics_BtnClick(object sender, EventArgs e)
        {
            Frm_Alarm2.Instance.Hide();
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Home.Instance.Hide();
            Frm_YieldStatistics.Instance.Show();
        }

        private void ucBtnImg_Alarm_BtnClick(object sender, EventArgs e)
        {
            Frm_Alarm2.Instance.dtp_StartDate.Text = DateTime.Now.AddDays(-1).ToString();
            Frm_Alarm2.Instance.dtp_EndDate.Text = DateTime.Now.ToString();
            Frm_Alarm2.Instance.dtp_StartTime.Text = DateTime.Now.ToString();
            Frm_Alarm2.Instance.dtp_EndTime.Text = DateTime.Now.ToString();

            Frm_Home.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Setting.Instance.Hide();
            Frm_YieldStatistics.Instance.Hide();
            Frm_Alarm2.Instance.Show();
        }

        private void ucBtnImg_Start_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Start();
        }

        private void ucBtnImg_Pause_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Pause();
        }
        private void ucBtnImg_Homing_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Intial();
        }
        private void ucBtnImg_Stop_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Stop();
        }

        private void ucBtnImg_OpenFile_BtnClick(object sender, EventArgs e)
        {
            if (FileUtils.IsExistDirectory(Common.dataSavePath))
            {
                Process.Start(Common.dataSavePath);
            }
            else
            {
                FileUtils.CreateDirectory(Common.dataSavePath);
                Process.Start(Common.dataSavePath);
            }
        }

        private void ucBtnImg_OpenPicture_BtnClick(object sender, EventArgs e)
        {
            if (FileUtils.IsExistDirectory(Common.picSavePath))
            {
                Process.Start(Common.picSavePath);
            }
            else
            {
                FileUtils.CreateDirectory(Common.picSavePath);
                Process.Start(Common.picSavePath);
            }
        }

        private void ucBtnImg_Login_BtnClick(object sender, EventArgs e)
        {
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Show();
            Frm_Home.Instance.Hide();
            Frm_Statistics.Instance.Hide();
            Frm_YieldStatistics.Instance.Hide();
            Frm_Alarm2.Instance.Hide();
        }

        private void ucBtnExt_MachineInfo_BtnClick(object sender, EventArgs e)
        {
            Dlg_Version.Instance.ShowDialog(this);
        }

        private void btn_PointCheckReview_BtnClick(object sender, EventArgs e)
        {
            Dlg_PointCheck pointCheckDlg = new Dlg_PointCheck();
            pointCheckDlg.Show();
        }
        #endregion

        #region 指纹锁
        public void RegiserLockProcess()
        {
            if (backgroundWorker1.IsBusy)
                return;
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            while (Common.msg.RegiserLockFlag)
            {
                Common.msg.nUserOptionsCount++;
                if (Common.msg.nUserOptionsCount > 5)
                {
                    //五分钟不动鼠标键盘时的执行操作函数。
                    Common.msg.nUserOptionsCount = 0;

                    Common.Authority = "OP";
                    Common.fingerPrintAuthority = "";

                    Frm_Login.Instance.SetPassCode();

                    string halconExamples = FileUtils.GetAppDirectory();

                    Common.isFileSetPassCode = true;
                    Common.ProcedurePath = halconExamples + @"\hdevengine\procedures.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}";

                    break;
                }

                Thread.Sleep(60000);
            }
        }

        private void background_DoWork()
        {
            while (Common.msg.RegiserLockFlag)
            {
                Common.msg.nUserOptionsCount++;
                if (Common.msg.nUserOptionsCount > 1000)
                {
                    //五分钟不动鼠标键盘时的执行操作函数。
                    Common.msg.nUserOptionsCount = 0;

                    Common.Authority = "OP";
                    Common.username = "Operator";
                    Frm_Setting.Instance.Hide();
                    Frm_Login.Instance.Hide();
                    Frm_Home.Instance.Show();
                    //Common.fingerPrintAuthority = "";

                    //Frm_Login.Instance.SetPassCode();
                }
                Thread.Sleep(200);
                //Application.DoEvents();
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Home.Instance.Show();
            Frm_Statistics.Instance.Hide();
            Frm_Alarm2.Instance.Hide();

            RegiserLockProcess();
        }

        #endregion

        #region 事件
        private void Frm_Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            MachineStatusManager.CurrentMachineStatus = MachineStatus.Quit;
            if (Common.HikVisionList != null)
            {
                foreach (var item in Common.HikVisionList)
                {
                    item.DisConnect();
                }
            }

            PublicMethod.StopMachine();
            Process.GetCurrentProcess().Kill();
            Application.Exit();
        }
        #endregion

        #region UI

        private void ucBtnImg_MouseEffected(object sender, EventArgs e)
        {
            var btn = sender as HZH_Controls.Controls.UCBtnExt;
            btn.FillColor = Color.FromArgb(238, 238, 237);
        }

        private void ucBtnImg_MouseEffecting(object sender, EventArgs e)
        {
            var btn = sender as HZH_Controls.Controls.UCBtnExt;
            btn.FillColor = Color.FromArgb(174, 218, 151);
        }


        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            Frm_InitItemStatu.Instance.Show(this);
        }

        private void Frm_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            Dlg_InputMsgComfirm inputMsgComfirmDlg = new Dlg_InputMsgComfirm(Configuration.language == Configuration.Language.Chinese ? "确认框" : "Confirm Dialog", Configuration.language == Configuration.Language.Chinese ? "确认关闭软件？" : "Close the Software Now?");
            if (inputMsgComfirmDlg.ShowDialog(this) == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
            else
            {
                DateTime startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").ToString());
                int timeCount = (endTime - startTime).Seconds;
                AlarmInfo alarmInfo = new AlarmInfo()
                {
                    StartTime = startTime,
                    EndTime = endTime,
                    TimeCount = timeCount,
                    Type = "软件关闭",
                    Description = "手动关闭软件，关闭原因：" + inputMsgComfirmDlg.msg
                };

                AlarmInfoServices AlarmInfoServices = new AlarmInfoServices();
                AlarmInfoServices.Add(alarmInfo);
            }
            Frm_Home.Instance.SaveYieldToIni();
        }

        private void settingToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            //if (Common.username == "Apple" || Common.username == "superadmin"
            //        || Common.username == "EN"
            //        || Common.username == "Battery QM")
            {
                if (e.ClickedItem == tsmi_MotionConfig)//运动参数配置
                {
                    Frm_MachineConfig.Instance.Show();
                }
            }
            //else
            //{
            //    MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return;
            //}

        }

        private void tsmi_OpenProject_Click(object sender, EventArgs e)
        {
            if (Common.username == "Apple" || Common.username == "superadmin" || Common.username == "EN" || Common.username == "Battery QM")
            {
                if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Homing || MachineStatusManager.CurrentMachineStatus == MachineStatus.Running)
                {
                    MessageBox.Show("设备正在运行，请先停止！");
                }
                OpenFileDialog mDialog = new OpenFileDialog();
                mDialog.Filter = "(*.gra)|*.gra";
                if (DialogResult.OK == mDialog.ShowDialog())
                {

                    Common.ProjectName = mDialog.SafeFileName.Split('.')[0];
                    MachineDataManager.ProjectName = Common.ProjectName;
                    ucBtnExt_MachineInfo.BtnText = Common.ProjectName;
                    MachineDataManager.Instance.Init();
                    MachineDataManager.LoadFromFile();

                    Frm_MachineConfig.Instance.ReloadProject();
                    if (Common.ProjectName == "Bolck")
                    {
                        Frm_Home.Instance.RefreshHomeUI(Common.ProjectName);
                    }
                    else
                    {
                        Frm_Home.Instance.RefreshHomeUI("Product");
                    }
                    Frm_Home.Instance.ReadHistoryData();
                    Machine.MachineResourceInit();
                }
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

        }

        private void tsmi_NewProject_Click(object sender, EventArgs e)
        {
            if (Common.username == "Apple" || Common.username == "superadmin" || Common.username == "EN" || Common.username == "Battery QM")
            {
                if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Homing || MachineStatusManager.CurrentMachineStatus == MachineStatus.Running)
                {
                    MessageBox.Show("设备正在运行，请先停止！");
                }
                Dlg_SelectProject selectProjectDialog = new Dlg_SelectProject();
                selectProjectDialog.Title = "新建项目";
                if (selectProjectDialog.ShowDialog(Frm_Home.Instance) != DialogResult.OK)
                {
                    return;
                }

                MachineDataManager.ProjectName = Common.ProjectName;
                ucBtnExt_MachineInfo.BtnText = Common.ProjectName;

                MachineDataManager.Instance.Init();
                MachineDataManager.LoadFromFile();

                Frm_MachineConfig.Instance.ReloadProject();
                if (Common.ProjectName == "Bolck")
                {
                    Frm_Home.Instance.RefreshHomeUI(Common.ProjectName);
                }
                else
                {
                    Frm_Home.Instance.RefreshHomeUI("Product");
                }

                Frm_Home.Instance.ReadHistoryData();
                Machine.MachineResourceInit();
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        public class UserOptionCheckBFMessage : IMessageFilter
        {
            public bool RegiserLockFlag = true;
            public int nUserOptionsCount = 0;

            public bool PreFilterMessage(ref Message m)
            {
                //检测鼠标或者键盘的消息
                if (m.Msg == 0x0200 || m.Msg == 0x0201 || m.Msg == 0x0204 || m.Msg == 0x0207)
                {
                    nUserOptionsCount = 0;
                }
                return false;
            }
        }


        private void btn_StartOnce_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确认要<—启用—> 启动一次 吗？", "确认", MessageBoxButtons.OKCancel);
            if (result == DialogResult.OK)
            {
                Common.StartOnce = true;
            }
        }

        bool isFrist = true;
        private void tscb_ProTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Initialized || MachineStatusManager.CurrentMachineStatus == MachineStatus.Ready)
            {
                if (tscb_ProTypeList.SelectedItem.ToString() != Common.CurProType)
                {
                    Common.CurProType = tscb_ProTypeList.SelectedItem.ToString();
                    Frm_Setting.Instance.DgvBindSource();

                    var ret = this.Invoke(new Action(() =>
                    {
                        PublicMethod.ChangeProjectExvent();
                    }));
                    Common.CurProTypeMeasureItems = Common.ProductTypeMeasureItemEnableList.Find(x => x.ProductType.Equals(Common.CurProType));
                    if (Common.CurProTypeMeasureItems == null)
                    {
                        Common.AppendUiLog.Log($"选择当前产品类型异常", LogType.Error);
                    }
                    Frm_Home.Instance.RefreshHomeUI(Common.CurProType);
                    PublicMethod.WriteCurProTypeIni(Common.CurProType);
                    Frm_Home.Instance.ReadHistoryData();
                }
                PublicMethod.ReadCSVFile();
            }
            else
            {
                if (isFrist == false)
                {
                    MessageBox.Show("禁止切换产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    isFrist = false;
                }
            }
        }

        private async void Btn_Click(object sender, EventArgs e)
        {
            switch ((sender as Button).Text)
            {
                case "联机模式":
                    PublicMethod.Pause();
                    PublicMethod.Stop();
                    tscb_ProTypeList.SelectedIndex = 0;
                    Btn_联机模式.BackColor = Color.Green;
                    Btn_脱机模式.BackColor = Color.Gray;
                    Btn_量块点检.BackColor = Color.Gray;
                    Common.Method_联机模式();
                    break;
                case "脱机模式":
                    PublicMethod.Pause();
                    PublicMethod.Stop();
                    //tscb_ProTypeList.SelectedIndex = 1;
                    Btn_联机模式.BackColor = Color.Gray;
                    Btn_脱机模式.BackColor = Color.Green;
                    Btn_量块点检.BackColor = Color.Gray;
                    Common.量块点检 = false;

                    break;
                default:
                    PublicMethod.Pause();
                    PublicMethod.Stop();
                    Btn_联机模式.BackColor = Color.Gray;
                    Btn_脱机模式.BackColor = Color.Gray;
                    Btn_量块点检.BackColor = Color.Green;
                    Btn_量块点检.Enabled = false;
                    tscb_ProTypeList.SelectedIndex = 3;// 2,3,4 对应大中小Block
                    Common.Method_量块点检();
                    Common.OmronPLC.Write(Common.PLCAdr.DicOutPutBool[PLCOutPutBool.GRR模式], true);
                    await Task.Run(async () =>
                    {
                        while (Common.量块点检)
                        {
                            await Task.Delay(500);
                        }
                    });
                    Btn_量块点检.Enabled = true;

                    Common.上次点检时间 = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                    MessageBox.Show("量块点检OK!");
                    break;
            }
        }

        private void Btn_SafeDoor_Click(object sender, EventArgs e)
        {
            if (Btn_SafeDoor.Text == "安全门已打开")
            {
                PublicMethod.SafeDoorWork(true);
            }
            else
            {
                PublicMethod.SafeDoorWork(false);

            }
        }

        private void PublicMethod_SafeDoorWorkAction(bool obj)
        {
            if (obj)
            {
                Btn_SafeDoor.Text = "安全门已关闭";
                Btn_SafeDoor.BackColor = Color.Green;
            }
            else
            {
                Btn_SafeDoor.Text = "安全门已打开";
                Btn_SafeDoor.BackColor = Color.Red;
            }
        }

        private void Btn_ClearAll_Click(object sender, EventArgs e)
        {
            if (Btn_ClearAll.Text == "未启用清料模式")
            {
                DialogResult result = MessageBox.Show("确认要<—启用—>清料模式吗？", "确认", MessageBoxButtons.OKCancel);
                if (result == DialogResult.OK)
                {

                    Common.OmronPLC.Write(Common.PLCAdr.DicOutPutBool[Module.StationLogic.PLCOutPutBool.整机清料信号], true);
                    Btn_ClearAll.Text = "已启用清料模式";
                    Btn_ClearAll.BackColor = Color.Red;
                }
            }
            else
            {
                DialogResult result = MessageBox.Show("确认要<—关闭—>清料模式吗？", "确认", MessageBoxButtons.OKCancel);
                if (result == DialogResult.OK)
                {
                    Common.OmronPLC.Write(Common.PLCAdr.DicOutPutBool[Module.StationLogic.PLCOutPutBool.整机清料信号], false);
                    Btn_ClearAll.Text = "未启用清料模式";
                    Btn_ClearAll.BackColor = Color.Green;
                }
            }
        }
    }
}